import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: false,
    username: ''
  }),
  actions: {
    login(username) {
      this.isLoggedIn = true
      this.username = username
      localStorage.setItem('user', JSON.stringify({
        isLoggedIn: true,
        username
      }))
    },
    logout() {
      this.isLoggedIn = false
      this.username = ''
      localStorage.removeItem('user')
    },
    initUser() {
      const user = localStorage.getItem('user')
      if (user) {
        const { isLoggedIn, username } = JSON.parse(user)
        this.isLoggedIn = isLoggedIn
        this.username = username
      }
    }
  }
})